package com.ermax.aircond.maintain.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.ermax.aircond.maintain.dao.MachineDao;
import com.ermax.aircond.maintain.domain.Building;
import com.ermax.aircond.maintain.domain.Floor;
import com.ermax.aircond.maintain.domain.Machine;
import com.ermax.aircond.maintain.domain.Room;
import com.ermax.aircond.util.dao.AbstractHibernateDao;

@Repository("machineDao")
public class MachineDao extends AbstractHibernateDao<Machine> implements java.io.Serializable{

	private static final long serialVersionUID = 1L;
	
	public MachineDao(){
		setClazz(Machine.class);
	}
	
	public List<Machine> findAll(String status){
		Criteria criteria = this.getCurrentSession().createCriteria(Machine.class);
		if(isNotNull(status)){
			criteria.add(Restrictions.eq("status", status));
		}
		@SuppressWarnings("unchecked")
		List<Machine> results = criteria.list();
		return results;
	}
	
	public Machine findMachineByGateAndDeviceNo(int gateNo, int deviceNo){
		Criteria criteria = this.getCurrentSession().createCriteria(Machine.class);
	
		criteria.add(Restrictions.eq("gateNo", gateNo));
		criteria.add(Restrictions.eq("deviceNo", deviceNo));
		
		@SuppressWarnings("unchecked")
		List<Machine> results = criteria.list();
		if(results.size() > 0){
			return results.get(0);
		}
		return null;
	}
	
	public List<Machine> findMachines(Building building, Floor floor, Room room, String keyword, String status) {
		Criteria criteria = this.getCurrentSession().createCriteria(Machine.class);
		Criteria roomCriteria = null;
		Criteria floorCriteria = null;
		
		if(isNotNull(room)){
			criteria.add(Restrictions.eq("room", room));
		}
		
		if(isNotNull(floor)){
			if(roomCriteria == null){
				roomCriteria = criteria.createCriteria("room");
			}
			roomCriteria.add(Restrictions.eq("floor", floor));			
		}
		

		if (isNotNull(building)) {
			if(roomCriteria == null){
				roomCriteria = criteria.createCriteria("room");
			}
			if(floorCriteria == null){
				floorCriteria = roomCriteria.createCriteria("floor");
			}
			floorCriteria.add(Restrictions.eq("building", building));	
		}				

		if (isNotNull(keyword)) {
			StringBuilder sbKey = new StringBuilder();
			sbKey.append("%");
			sbKey.append(keyword);
			sbKey.append("%");
			String key = sbKey.toString();

			criteria.add(Restrictions.like("machineName", key));			
		}
		
		if(isNotNull(status)){
			criteria.add(Restrictions.eq("status", status));
		}

		@SuppressWarnings("unchecked")
		List<Machine> results = criteria.list();
		return results;
	}
		

}
